import {Component} from "@angular/core";
import {AlertController, IonicPage, ModalController, NavController, NavParams, ToastController} from "ionic-angular";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {AppUrl} from "../../../app/app.general";
import {AppConfig} from "../../../app/appConfig";
import {CashModalsPage} from "./cash-modals";
import {RequestOptions} from "@angular/http";

@IonicPage()
@Component({
  templateUrl: 'business-food-cashdetail.html',
  selector: 'business-food-cashdetail'
})

export class CashdetailPage {

  private tableSite = {
    used: {name: '已开台', color: '#389cf4'},
    waitForClean: {name: '待清理', color: 'brown'},
    ordered: {name: '已预订', color: 'coral'},
    stopToUse: {name: '暂停使用', color: 'black'},
    Idle: {name: '空闲', color: '#41b883'},
    cancel: {name: '取消', color: '#41b883'}
  };

  orderTable: Array<{ floor: number, tableSite: Array<{ name: string, color: string }>,
    goods: Array<{ goodname: string, goodprice: number, sumBuy: number, sumPrice: number, isbuy: boolean }> }>;

  cashType: string;
  private tableName: string;
  private sumCount: any;
  realGet: any;
  bal: any;
  private orderDetail: any;
  listDetail:any= [];
  imgsrc:any;
  // appconfig:AppConfig=null;

  private floor: number;
  orderno:string;
  callback:any;
  tableid:number;
  pagetitle:string;
  private receive:string = '应收';
  msgtext:any;


  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public navParam: NavParams, private http: HttpClient,
              public toastCtrl:ToastController,public modalCtrl:ModalController,public appConfig:AppConfig) {
    this.floor = this.navParam.get('floor');
    this.tableName = this.navParam.get('data').tablename;
    this.orderno=this.navParam.get('data').orderno;
    this.tableid=this.navParam.get('data').tableid;
    this.pagetitle=this.navParam.get('pagetitle');
    this.sumCount = this.navParam.get('data').sumPrice;
    this.orderDetail = this.navParam.get('data');
    if(this.orderno!=null){
      console.log(this.orderno);
      this.http.post(AppUrl.food.cashDetail,{orderno:this.orderno}).subscribe(data=>{
        console.log(data);
        let temp:any=data;
        this.listDetail=temp.data;
      });
    }else{
      console.log(this.tableid);
      this.http.post(AppUrl.food.cashInfo,{tableno:this.tableid}).subscribe(data=>{
        console.log(data);
        let temp:any=data;
        this.listDetail=temp.data;
        this.sumCount=this.listDetail[0].totalprice;
        this.orderno=this.listDetail[0].orderno;
      });
    }
    this.cashType='2';
    this.callback=this.navParam.get('callback');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad businessfoodcashdetail--------');
  }

  /*
  *取消该桌用餐
   */
  cancelCash() {
    console.log("------>>");
    return new Promise((resolve, reject) => {
      let alert = this.alertCtrl.create({
        title: '取消用餐',
        message: '是否确认取消本桌用餐?',
        buttons: [
          {
            text: '取消用餐',
            handler: () => {
              this.http.post(AppUrl.food.canceldining,{id:this.tableid,status:'0',orderno:this.orderno}).subscribe(data=>{
                this.callback({floor:this.floor,tableNo:this.tableName}).then(() => {
                  this.navCtrl.pop();
                });
              });
            }
          },
          {
            text: '不取消',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
      resolve();
    });
  }

  /*
  *计算找零
   */
  countBal() {
    // console.log("------>>" + this.realGet);
    if (this.realGet == '') {
      // console.log("-********>>");
      this.bal = '';
    } else {
      this.bal = this.realGet - this.sumCount;
    }
    this.receive = '收款'+this.realGet+'元     找零'+this.bal+'元';
  }

  settle(){
    let _that = this;
    if(this.realGet==null || this.realGet<0){
      let alert = this.alertCtrl.create({
        title: '未结算!',
        subTitle: '请输入结算金额!',
        buttons: ['确认']
      });
      alert.present();
    }else{
      //付款方式为0-现金;1-银行卡;2-扫码
      if(this.cashType=='0'){
        this.http.post(AppUrl.table.settle,{id:this.tableid,status:'3',orderno:this.orderno,payflag:'1',paytype:this.cashType,
          realpay:this.realGet,orderstatus:'1'}).subscribe(data=>{
          console.log(data);
          let temp:any=data;
          if(temp.code==200){
            this.callback({floor:this.floor,tableNo:this.tableName}).then(() => {
              this.navCtrl.pop();
            });
          }
        });
      }else{
        this.appConfig.connetWebSocket();
        this.msgtext=this.appConfig.wsMsg;
        let date:any=new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+new Date().getDate()+' '+new Date().getHours()+':'+new Date().getMinutes()+':'+new Date().getSeconds();
        let data1:any='{"qrCodeId": "","systemId": "3003","shop_id": "898340149000005","devno": "88880001","order_id": "20171102142900734561",' +
          '"msgSrc":"CHINATVPAY","msgType":"bills.getQRCode","totalAmount":"1","qrCodeType":"1","requestTimestamp":"'+date+'","instMid":"QRPAYDEFAULT"}';
        let headers = new HttpHeaders({
          'Content-Type':  'application/json',
          'Access-Control-Allow-origin':'*'
        });
        this.http.get(AppUrl.aliPay.testpay+data1,{headers:headers}).subscribe(data=>{
          this.msgtext='成功请求';
          console.log(data);
          let temp:any=data;
          console.log(temp.msg);

          if(temp.code==0){
            let id=temp.qrCodeId;
            this.imgsrc=AppUrl.food.getcode+'/'+id;
            this.appConfig.presentModal('CashModalsPage',{imgsrc:this.imgsrc});
            var msg:any;
            this.appConfig.websocket.onmessage = function (event) {
              console.log('看看返回些什么');
              console.log(event);
              let temp:any=event;
              let data:any=temp.data;
              msg=JSON.parse(data);
              console.log(data);
              console.log(msg);
              if(msg.code=='0'){
                _that.appConfig.colseModal();
                _that.http.post(AppUrl.table.settle,{id:_that.tableid,status:'3',orderno:_that.orderno,payflag:'1',paytype:_that.cashType,
                  realpay:_that.realGet,orderstatus:'1'}).subscribe(data=>{
                  console.log(data);
                  let temp:any=data;
                  if(temp.code==200){
                    _that.callback({floor:_that.floor,tableNo:_that.tableName}).then(() => {
                      _that.navCtrl.pop();
                    });
                  }
                });
              }else{
                let toast = _that.toastCtrl.create({
                  message: msg.msg,
                  duration: 3000
                });
                toast.present();
              }
              // _that.appConfig.websocket.close();
            };
          }else{
            let toast = this.toastCtrl.create({
              message: temp.msg,
              duration: 3000,
              position: 'bottom'
            });
            toast.present();
          }
        },(error)=>{
          console.log('请求出错啦');
          console.log(JSON.stringify(error));
          let temp:any=error;
          this.msgtext=temp.message;
          console.log(error);
          // this.appConfig.websocket.close();
        });
      }
    }
  }
}
